package cn.crex1.xiaomi.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.crex1.xiaomi.vo.UserVO;


/**
 * 验证码工具类
 * @author Administrator
 *
 */
public class RandomCodeUtil {
	//判断用户输入的验证码与session中的是否一致
//	codeName:表示session中存的验证码名称
	public static Boolean equalsRandomCode(HttpServletRequest req) {
		String code=req.getParameter("code");//从前端获取输入的验证码
		String code1= (String) req.getSession().getAttribute("codes");
		System.out.println(code+"code");
		System.out.println(code1+"code1");
		return code.equals(code1);
		
	}
/**
 * 生成验证码方法
 * @throws IOException 
 */
	public static void createRandomCode(HttpServletRequest req,HttpServletResponse resp) throws IOException {
		//使用UUID获取随机数/并转换为字符串截取最前面的5位数
		 String randomCode=UUID.randomUUID().toString().substring(0, 5);
		//把随机数放进session中/并取名为codeName,赋值randomCode
		 req.getSession().setAttribute("codes", randomCode);
		 
//		UserVO userVO=new UserVO();
//		userVO.setCode(randomCode);
		//创建图片对象
		int width=100;
		int height=40;
		int imageType=BufferedImage.TYPE_INT_BGR;
		BufferedImage image=new BufferedImage(width, height, imageType);
		//画板
		Graphics graphics=image.getGraphics();
		graphics.setColor(Color.pink);
		//绘制实心的矩形
		graphics.fillRect(1, 1, width-2, height-2);
		//把随机数画进图中
		graphics.setColor(Color.BLACK);//设置随机数颜色为黑色
		Font font=new Font("宋体", Font.BOLD+Font.ITALIC, 22);
		graphics.setFont(font);//设置随机数的字体和大小
		graphics.drawString(randomCode, 10,28);
		//干扰线
		graphics.setColor(Color.GRAY);
		Random r=new Random();
		for(int i=0;i<100;i++) {
			graphics.fillRect(r.nextInt(width), r.nextInt(height), 2, 2);
		}
		//关闭
		graphics.dispose();
		//把图片对象以流的方式保存出去
		ImageIO.write(image, "jpg", resp.getOutputStream());
		
		
	}

}
